import Vue from 'vue';
import Vuex from 'vuex';

Vue.use(Vuex);

export default new Vuex.Store({
  state: {
    userInfo: {
      username: '',
      avatar: '',
      email: '',
      bio: '', // 新增个人签名字段
      isAdmin: false,
      status: true,
    }
  },

  mutations: {
    // 设置用户信息
    setUserInfo(state, userInfo) {
      state.userInfo = userInfo;
    },
    // 清空用户信息
    CLEAR_USER_INFO(state) {
      state.userInfo = {
        username: '',
        avatar: '',
        email: '',
        bio: '', // 确保清空 bio 字段
        isAdmin: false,
        status: true,
      };
    }
  },

  actions: {
    // 获取用户信息
    async fetchUserInfo({ commit }) {
      const token = sessionStorage.getItem('jwt_token'); // 从 sessionStorage 获取 token
      if (token) {
        try {
          // 向后端发送请求获取用户信息
          const response = await fetch('http://localhost:5000/user/userinfo', {
            headers: {
              Authorization: `Bearer ${token}`,
            }
          });
          const data = await response.json();

          // 假设返回的数据结构包含 username, avatar, email, bio, is_admin 和 status
          if (data.username) {
            commit('setUserInfo', {
              username: data.username,
              avatar: data.avatar || '', // 头像可能为空
              email: data.email,
              bio: data.bio || '',  // 如果 bio 为空，则默认为空字符串
              isAdmin: data.is_admin,
              status: data.status,
            });
          }
        } catch (error) {
          console.error('获取用户信息失败', error);
        }
      }
    }
  },

  getters: {
    userInfo: state => state.userInfo,
    isAdmin: state => state.userInfo.isAdmin,
  }
});
